/**
* Created by GoLand.
* User: link1st
* Date: 2019-07-25
* Time: 09:59
 */

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"gowebsocket/lib/redislib"
	"gowebsocket/routers"
	"gowebsocket/servers/grpcserver"
	"gowebsocket/servers/task"
	"gowebsocket/servers/websocket"
	"io"
	"net/http"
	"os"
	"os/exec"
	"time"
)

func main() {
	initConfig()//初始化config

	initFile()//初始话日志

	initRedis()//初始化redis

	router := gin.Default()//初始化gin框架使用
	// 初始化路由
	routers.Init(router)//初始化web路由
	routers.WebsocketInit()//初始化websocket路由

	// 定时任务 清理过期断连的用户连接
	task.Init()

	// 服务注册
	task.ServerInit() //定时初始化server连接参数到redis中 服务器心跳 定时检测

	go websocket.StartWebSocket()
	// grpc
	go grpcserver.Init()

	go open()

	httpPort := viper.GetString("app.httpPort")
	http.ListenAndServe(":"+httpPort, router)

}

// 初始化日志
func initFile() {
	// Disable Console Color, you don't need console color when writing the logs to file.
	gin.DisableConsoleColor()// 禁用控制台颜色

	// Logging to a file.
	logFile := viper.GetString("app.logFile")
	f, _ := os.Create(logFile)//创建日志文件
	gin.DefaultWriter = io.MultiWriter(f)//设置默认写入log文件的句柄
}

func initConfig() {
	viper.SetConfigName("config/app")//查询config文件夹下的app.yaml
	viper.AddConfigPath(".") // 添加搜索路径 以当前路径出发

	err := viper.ReadInConfig()//读取配置
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	fmt.Println("config app:", viper.Get("app"))
	fmt.Println("config redis:", viper.Get("redis"))

}

func initRedis() {
	redislib.ExampleNewClient()
}

func open() {

	time.Sleep(10000 * time.Millisecond)

	httpUrl := viper.GetString("app.httpUrl")
	httpUrl = "http://" + httpUrl + "/home/index"

	fmt.Println("访问页面体验:", httpUrl)

	cmd := exec.Command("open", httpUrl)
	_, err := cmd.Output()
	fmt.Println(err)
}
